<template>
  <div class="app-container">
    <div v-if="showSearch" class="search-container">
      <CommonSearch
        :formConfig="searchColumns"
        :inline="true"
        labelWidth="auto"
        formItemWidth="auto"
        :model="searchParam"
      >
        <template #after>
          <el-button type="primary" @click="startSearch">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="startReset">
            <i-ep-refresh />
            重置
          </el-button>
        </template>
      </CommonSearch>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- 表格内容操作 -->
        <template v-for="item in tableColumns" :key="item">
          <TableColumn v-if="item.prop && item.isShow" :column="item">
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
              <slot :name="slot" v-bind="scope"></slot>
            </template>
          </TableColumn>
        </template>
        <el-table-column fixed="right" label="操作" width="280" align="center">
          <template #default="scope">
            <el-button
              type="info"
              size="small"
              link
              @click="jumpPage(scope.row.id, 3)"
              >预览</el-button
            >
            <el-button
              type="warning"
              size="small"
              link
              @click="jumpPage(scope.row.id, 1)"
              >管理页面</el-button
            >
            <el-button
              type="success"
              size="small"
              link
              @click="jumpPage(scope.row.id, 2)"
              >设计</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="handleTableDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <sysworkbenchinfo-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :belongUserId="workbenchPageId"
      @reset-table="(id:string) => (id?.length ? startSearch() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 列设置 抽屉组件 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
    />
  </div>
</template>

<script setup lang="tsx">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { getUserInfo } from "@/api/user";
import router from "@/router";
import { useUserStore } from "@/store/modules/user";
defineOptions({
  name: "SYSTEMPERSONALWORKBENCHLIST",
  inheritAttrs: false,
});

/** 自定义设置方法   start **/

// 搜索参数 设置为响应式
const searchColumns: any = reactive([
  {
    type: "input", // 普通输入框
    isShow: true,
    inputType: "text", // 类型, text/textarea
    label: "工作台编号", // 标签文本
    fieldName: "workbenchCode", // 字段名称
    placeholder: "请输入工作台编号", // 提示文字
    initValue: "", // 默认值
  },
  {
    type: "input", // 普通输入框
    isShow: true,
    inputType: "text", // 类型, text/textarea
    label: "工作台名称", // 标签文本
    fieldName: "workbenchName", // 字段名称
    placeholder: "请输入工作台名称", // 提示文字
    initValue: "", // 默认值
  },
  {
    type: "select",
    label: "工作台类型",
    isShow: true,
    fieldName: "workbenchType",
    placeholder: "请选择工作台类型",
    initValue: null,
    defaultFirstOption: true,
    optionList: useDictionary("WorkbenchType"),
  },
]);

// 接收 columns 并设置为响应式
const tableColumns = reactive([
  { prop: "workbenchCode", label: "工作台编号", isShow: true, minWidth: "100" },
  { prop: "workbenchName", label: "工作台名称", isShow: true, minWidth: "100" },
  {
    prop: "workbenchType",
    label: "工作台类型",
    width: 120,
    isShow: true,
    render: (scope: any) => (
      <el-tag>{useDictionary("WorkbenchType", scope.row.workbenchType)}</el-tag>
    ),
  },
  {
    prop: "isPublic",
    label: "公共模板",
    width: 120,
    isShow: true,
    render: (scope: any) =>
      scope.row.isPublic === 1 ? (
        <el-tag type="success">
          {useDictionary("IsPublic", scope.row.isPublic === 1 ? "1" : "0")}
        </el-tag>
      ) : (
        <el-tag>{useDictionary("IsPublic", scope.row.isPublic)}</el-tag>
      ),
  },
  {
    prop: "remarks",
    label: "备注",
    isShow: true,
    minWidth: "100",
    render: (scope: any) => <span>{scope.row.remarks || "--"}</span>,
  },
]);

// 是否显示搜索框
const showSearch = ref(true);

/** 列表项自定义方法   end **/

function jumpPage(id: string, type: number) {
  router.push({
    path:
      type === 1
        ? "/system/sysworkbenchinfo/workbenchPageManage"
        : type === 2
        ? "/system/sysworkbenchinfo/workbenchPageDesign"
        : "/system/sysworkbenchinfo/workbenchPagePreview",
    query: {
      workbenchId: id,
    },
  });
}
// 请求参数
const requestApi = "/system/sysworkbenchinfo/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
let searchParamInit = {
  workbenchCode: "",
  workbenchName: "",
  workbenchType: "",
  belongUserId: "",
};

const deleteParam = {
  api: "/system/sysworkbenchinfo/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

const DASHBOARD_ID = import.meta.env.VITE_APP_DASHBOARD_ID;
const workbenchPageId = ref("");
// 获取当前用户信息

onMounted(async () => {
  // 获取当前用户信息
  // console.log();

  // let res = await getUserInfo();
  workbenchPageId.value = useUserStore().user.userId;
  searchParam.value.belongUserId = workbenchPageId.value;
  getTableList();

  // request({
  //   url: `/system/sysworkbenchinfo/getPersonal/${DASHBOARD_ID}`,
  //   method: "get",
  //   data: {},
  // }).then((res) => {
  //   workbenchPageId.value = res.data.id || DASHBOARD_ID;
  //   searchParam.value.belongUserId = workbenchPageId.value;
  //   getTableList();
  // });
});

function startSearch() {
  searchParam.value.belongUserId = workbenchPageId.value;
  search();
}

function startReset() {
  searchParam.value = { ...searchParamInit };
  searchParam.value.belongUserId = workbenchPageId.value;
  pageable.value.pageNum = 1;
  search();
}

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/system/sysworkbenchinfo/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开工作台信息表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改工作台信息";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增工作台信息";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开工作台信息表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "工作台信息详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
</script>
